var co = require('co')
var OSS = require('ali-oss')

/**
 * OssProperties = {
    region: _this.region,
    accessKeyId: result.accessKeyId,
    accessKeySecret:result.accessKeySecret,
    stsToken: result.SecurityToken,
    bucket: _this.bucket
  }
 * @param OssProperties
 */
var client
export function uploadOss (resp, file, func) {
  file = file.file
  client = new OSS.Wrapper({
    region: resp.region,
    accessKeyId: resp.accessId,
    accessKeySecret: resp.accessKey,
    bucket: resp.privateBucket
  });
  // 随机命名
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  var maxPos = chars.length
  var randomstring = ''
  for (var i = 0; i < 10; i++) {
    randomstring += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  var pos = file.name.lastIndexOf('.')
  var suffix = ''
  if (pos != -1) {
    suffix = file.name.substring(pos)
  }
  var randomname = resp.baseDir + '/' + randomstring + new Date().getTime() + suffix;

  co(function* () {
    client.put(randomname, file)
  }).catch(function (err) {
    console.error('error: %j', err)
  })
  setTimeout(() => {
    func('/' + randomname);
  }, 1000)
}
